/**
 * 行政老师修改岗位详情
 * 
 * /xingzheng/company/update
 */


const Companies = require('../../../models/companys')
const utils = require('../../../utils/index')
const $ = require('../../../utils/common')

const updata = async function (req, res) {
    try {

        delete req.body.createdAt
        delete req.body.updatedAt
        delete req.body.company_year
        // 找到当前报名人数，所需人数不能少于当前报名人数
        delete req.body.current_student
        delete req.body.id

        if (!req.body.company_id) {
            $.sendMessage(res, 1015, 'company_id 不能缺少')
            return
        }

        var company = await Companies.findOne({ 
            where: {
                id: req.body.company_id
            }
        })

        if (req.body.student_limit) {
            if (!$.isNumber(req.body.student_limit)) {
                $.sendMessage(res, 1015 , 'student_limit为数字类型')
                return
            }

            if (parseInt(req.body.student_limit) < company.dataValues.current_student) {
                $.sendMessage(res, 1015 , '修改的所需人数不能少于当前的报名人数')
                return
            }

            if (parseInt(req.body.student_limit) < 1 ) {
                $.sendMessage(res, 1015 , '所需人数不能小于1')
                return
            }
        }
        
        var updata = await Companies.update(
            req.body,
            {
                where: {
                    id: req.body.company_id
                }
            }
        )

        if (updata[0] == '1') {
            res.json({
                code: 200,
                message: '编辑成功',
            })

            // 日志
            utils.create_a_log(req, '岗位管理', '编辑详情')
            return
        }

        // 异常
        res.json({
            code: 0000,
            message: '代码错误，请联系管理员'
        })
            
        utils.create_a_log(req, '岗位管理', '编辑详情', '失败')
        return
    }
    catch(error) {
        res.json({
            message: "抓到异常",
            error: 'error' + error
        })

        utils.create_a_log(req, '岗位管理', '编辑详情', '失败')
        return
    } 
}
    
module.exports = updata